<?php


namespace app\user\controller;

use app\common\Tools;
use think\Db;
use think\facade\Request;

/**
 * Class Receivables 应收款项
 * @package app\user\controller
 */
class Receivables extends LoggingBase
{
    /**
     * 界面：回款列表
     */
    public function Listing()
    {
        $UserID = $this->m_User->ID;
        $CompanyID = $this->m_User->CompanyID;
        $ClientData = Db::table('client')->field('ID,Name,Contacts')->where("IsDeleted='0' AND OwnerType='1' AND OwnerID='$UserID'")->select();
        $this->assign('Clients', $ClientData);

        $this->assign('UserID', $UserID);

        $UserData = Db::table('user')->field('u.ID,u.Nick,cd.Name AS DepartmentName')->alias('u')
            ->leftJoin('company_department cd', 'cd.ID=u.DepartmentID')->where("u.IsDeleted='0' AND u.CompanyID='$CompanyID'")->select();
        $this->assign('Users', $UserData);

        $Css = array(
            '<link href="/layui/css/layui.css" rel="stylesheet"/>'
        );
        return $this->mb_Display('回款列表', 'ReceivablesList', 'listing', $Css);
    }

    /**
     * 接口：回款列表
     */
    public function mb_Listing()
    {
        $Page = Request::has('page') ? Request::param('page') : 1;
        $Limit = Request::has('limit') ? Request::param('limit') : 9999999;
        $Type = Request::has('Type') ? Request::param('Type') : 0;  //0：全部，1：我提交的，2：我审核的
        $Keyword = Request::has('Keyword') ? Request::param('Keyword') : '';

        $OrderField = Request::has('OrderField') ? Request::param('OrderField') : '';
        $OrderType = Request::has('OrderType') ? Request::param('OrderType') : 'null';

        if ($OrderType == 'null') {
            $OrderField = 'ID';
            $OrderType = 'DESC';
        }

        $UserID = $this->m_User->ID;
        $Where = '';
        if ($Keyword != '') {
            $Where .= " AND (r.Number LIKE '%$Keyword%' OR c.Name LIKE '%$Keyword%') ";
        }
        if ($Type == 0) {
            $Where .= " AND (r.UserID='$UserID' OR r.AuditorID='$UserID') ";
        } else if ($Type == 1) {
            $Where .= " AND r.UserID='$UserID' ";
        } else if ($Type == 2) {
            $Where .= " AND r.AuditorID='$UserID' ";
        }

        $Count = Db::table('receivables')->field('r.ID')->alias('r')->leftJoin('client c', 'c.ID=r.ClientID')->where("r.IsDeleted='0' $Where")->count();
        $Data = Db::table('receivables')->field('r.ID,r.UserID,u.Nick AS UserNick,r.Number,c.ID AS ClientID, c.Name AS ClientName,cr.ID AS ContractID, cr.Number AS ContractNumber,r.Date,r.Type,r.Money,r.Remark,ua.ID AS AuditorID, ua.Nick AS AuditorName,r.Status,r.FileUrls')
            ->alias('r')
            ->leftJoin('client c', 'c.ID=r.ClientID')
            ->leftJoin('contract cr', 'cr.ID=r.ContractID')
            ->leftJoin('user u', 'u.ID=r.UserID')
            ->leftJoin('user ua', 'ua.ID=r.AuditorID')
            ->where("r.IsDeleted='0' $Where")->order($OrderField, $OrderType)->page($Page)->limit($Limit)->select();

        mb_OutMessage(ErrCode_Normal, '', $Data, $Count);
    }

    /**
     * 新增或編輯回款
     */
    public function mb_Submit()
    {
        $ReceivablesID = Request::has('ReceivablesID') ? Request::param('ReceivablesID') : 0;
        $Number = Request::has('Number') ? Request::param('Number') : '';
        $ClientID = Request::has('ClientID') ? Request::param('ClientID') : 0;
        $ContractID = Request::has('ContractID') ? Request::param('ContractID') : 0;
        $Date = Request::has('Date') ? Request::param('Date') : '';
        $Type = Request::has('Type') ? Request::param('Type') : '';
        $Money = Request::has('Money') ? Request::param('Money') : 0;
        $FileUrls = Request::has('FileUrls') ? Request::param('FileUrls') : '';
        $AuditorID = Request::has('AuditorID') ? Request::param('AuditorID') : '';
        $Remark = Request::has('Remark') ? Request::param('Remark') : '';
        $Status = Request::has('Status') ? Request::param('Status') : '';

        if (!$ClientID) mb_OutMessage(ErrCode_Toast, '请选择客户');
        if (!$ContractID) mb_OutMessage(ErrCode_Toast, '请选择合同');
        if (!$Date) mb_OutMessage(ErrCode_Toast, '请选择日期');
        if (!$Type) mb_OutMessage(ErrCode_Toast, '请选择回款方式');
        if (!$Money) mb_OutMessage(ErrCode_Toast, '请选择回款金额');

        $UserID = $this->m_User->ID;
        Db::startTrans();
        try {
            if($Number == '')$Number = 'RECEIPT-'.date('Ymd').'-'.rand(1000,9999);
            $Data = array(
                'UserID'=>$UserID,
                'Number'=>$Number,
                'ClientID'=>$ClientID,
                'ContractID'=>$ContractID,
                'Date'=>$Date,
                'Type'=>$Type,
                'Money'=>$Money,
                'Remark'=>$Remark,
                'AuditorID'=>$AuditorID,
                'FileUrls'=>$FileUrls,
                'Status'=>$Status
            );
            if($ReceivablesID == 0){
                //新增
                Db::table('receivables')->insert($Data);
            } else {
                //编辑
                $Data['ID'] = $ReceivablesID;
                Db::table('receivables')->update($Data);
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            mb_OutMessage(ErrCode_Toast, $e->getMessage());
        }
        mb_OutMessage(ErrCode_Normal,'保存成功');
    }

    /**
     * 导出回款记录
     */
    public function mb_Export()
    {
        $IDs = Request::has('IDs') ? Request::param('IDs') : '';
        if (!$IDs) mb_OutMessage(ErrCode_Toast, '请先搜索记录');

        $Data = Db::table('receivables')->field('r.Number,c.Name AS ClientName,cr.Number AS ContractNumber,r.Date,r.Type,r.Money,r.Remark,ua.ID AS AuditorID, ua.Nick AS AuditorName,r.Status,r.FileUrls')
            ->alias('r')
            ->leftJoin('client c', 'c.ID=r.ClientID')
            ->leftJoin('contract cr', 'cr.ID=r.ContractID')
            ->leftJoin('user ua', 'ua.ID=r.AuditorID')
            ->where("r.IsDeleted='0' AND r.ID IN ( $IDs )")->select();

        $SetWidths = [30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30];
        $Titles = ['回款编号', '客户名称', '合同编号', '回款日期', '回款方式', '回款金额', '备注', '审核人', '状态'];
        $Contents = array();
        foreach ($Data as $Key => $Val) {
            $Temp = array(
                $Val['Number'],
                $Val['ClientName'],
                $Val['ContractNumber'],
                $Val['Date'],
                $this->mb_GetTypeName($Val['Type']),
                $Val['Money'],
                $Val['Remark'],
                $Val['AuditorName'],
                $this->mb_GetStatusName($Val['Status'])
            );
            $Contents[] = $Temp;
        }
        $FileName = '回款资料导出_' . date('YmdHis') . '_' . rand(100, 999) . '.xls';
        Tools::mb_ExportExcel($Titles, $Contents, $_SERVER['DOCUMENT_ROOT'] . '/uploads/files/' . $FileName, $SetWidths);
        mb_OutMessage(ErrCode_Normal, '导出成功', ['url' => Request::domain() . '/uploads/files/' . $FileName]);
    }

    private function mb_GetTypeName($Type){
        //回款方式（1：支票，2：現金，3：邮政汇款，4：电汇，5：网上转账，6：支付宝，7：微信支付，8：其他）
        $TypeName = '支票';
        if($Type == 2){
            $TypeName = '现金';
        } else if($Type == 3){
            $TypeName = '邮政汇款';
        } else if($Type == 4){
            $TypeName = '电汇';
        } else if($Type == 5){
            $TypeName = '网上转账';
        } else if($Type == 6){
            $TypeName = '支付宝';
        } else if($Type == 7){
            $TypeName = '微信支付';
        } else if($Type == 8){
            $TypeName = '其他';
        }
        return $TypeName;
    }

    private function mb_GetStatusName($Status){
        $StatusName = '草稿';//狀態（1：草稿，2：待審核，3：審核通過，4：審核不通過）
        if ($Status == 2) {
            $StatusName = '待审核';
        } else if ($Status == 3) {
            $StatusName = '审核通过';
        } else if ($Status == 4) {
            $StatusName = '审核不通过';
        }
        return $StatusName;
    }
}